package com.itheima.security;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * SpringSecurityUserService给查询到的用户动态添加角色，授权
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获取用户对象
        com.itheima.pojo.User user=userService.findByUsername(username);
        //判断用户是否存在
        if(user==null){
            return null;
        }
        //将授权信息返回给框架
        List<GrantedAuthority> list = new ArrayList<>();
        //角色信息
        Set<Role> roles = user.getRoles();//当前角色集合为空
        for (Role role : roles) {
            /**
             *授予角色
             * SimpleGrantedAuthority实现了GrantedAuthority
             */
            list.add(new SimpleGrantedAuthority(role.getKeyword()));//ROLE_xxx
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        UserDetails userDetails = new User(username,user.getPassword(),list);
        return userDetails;
    }
}
